<template>
  <div>
    <myDivider name="房间管理"></myDivider>
    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="this.operateType == 'update' ? '修改房间信息' : '新增房间信息'">
    </el-page-header>
    <div class="insertPopulation">
      <el-form ref="reinsertForm" :model="reinsertForm" label-width="80px" :inline="true" :rules="insertRules">
        <el-form-item label="房间名称:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input v-model="reinsertForm.name" maxlength="100" placeholder="请输入房间名称" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="所在楼宇:" :label-width="formLabelWidth" class="formItemStyle" prop="" required>
          <el-select disabled v-model="reinsertForm.buildingId" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in buildingIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单元楼:" :label-width="formLabelWidth" class="formItemStyle" prop="unitCode">
          <el-select v-model="reinsertForm.unitCode" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in unitCodeData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="房型:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.layout" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in layoutData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="层数:" prop="floors" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="reinsertForm.floors"  oninput="if(value.length > 4) value=value.slice(0, 4)" @input="reinsertForm.floors = reinsertForm.floors.replace(/[^\d]/g, '')" type="number" placeholder="请输入层数" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="占地面积:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="reinsertForm.floorSpace" type="number" placeholder="请输入占地面积" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="权属类型:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.ownershipType" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in ownershipTypeData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="装修情况:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.decorationSituation" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in decorationSituationData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="房间朝向:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.toward" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in towardData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="房屋归属:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.ownership" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in ownershipData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产权证书:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.roomCertificateForm" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in roomCertificateFormData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房产证:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.hasOwnershipCertificate" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in hasOwnershipCertificateData" :key="item.type" :label="item.name"
              :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="证书编号:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="reinsertForm.certificateNumber"  @input="reinsertForm.certificateNumber = reinsertForm.certificateNumber.replace(/[^\d]/g, '')" placeholder="请输入证书编号" type="number" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="房主姓名:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="reinsertForm.ownerName" placeholder="请输入房主姓名" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="是否是公共区域" :label-width="formLabelWidth" class="formItemStyle">
          <template>
            <el-radio v-model="reinsertForm.isPublic" :label="0">私人区域</el-radio>
            <el-radio v-model="reinsertForm.isPublic" :label="1">公共区域</el-radio>
          </template>
        </el-form-item>
      </el-form>

      <!-- 添加取消 -->
      <el-form ref="form" :model="reinsertForm" label-width="80px" style="height: 41px;">
        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="this.operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="this.operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
    </div>
  </div>
</template>



<script>
import VDistpicker from "v-distpicker";
import { getUserList } from "../../user/user";
import {
  getFatherAgencies,
  addXiaoQu,
  getDictionaryList,
  getInDetail,
  updateinstInfo,
  getcityList,
  getShangJiJiGouList,
  addbuilding,
  getChaoXianglist,
  getJieGoulist,
  getYongTUlist,
  getTypelist,
  getXiaLaList,
  getAddedUserList,
  addroom
} from "./room";
export default {
  components: { VDistpicker },
  data() {
    return {
      decorationSituationData: [],
      buildingIdData: [],
      unitCodeData: [],
      layoutData: [],
      ownershipTypeData: [],
      towardData: [],
      ownershipData: [],
      roomCertificateFormData: [],
      hasOwnershipCertificateData: [],
      //下拉类型列表
      typeData: [{ name: "经济型", type: "1" }],
      // 下拉用途列表
      purposeData: [],
      // 结构下拉列表
      structureData: [],
      //朝向下拉列表
      towardData: [],
      //小区下拉列表
      residentialQuartersIdData: [],

      affiliatedManagementDepartmentIdData: [],
      affiliatedAgencyIdData: [],
      developerCompanyIdData: [{ name: "1号", type: 1 }],
      contractorCompanyIdData: [{ name: "1号", type: 1 }],
      criCodeDefaultShow: true,
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          let { level } = node;
          getcityList(node.value).then(res => {
            res.forEach(el => {
              el.value = el.criCode;
              el.label = el.criName;
              el.leaf = level >= 3;
            });
            resolve(res);
          });
        }
      },
      options: [],


      formLabelWidth: "120px", //控制前面label的宽度

      reinsertForm: {
        name: "",
        buildingId: "",
        unitCode: "",
        layout: "",
        floors: "",
        floorSpace: "",
        ownershipType: "",
        decorationSituation: "",
        toward: "",
        ownership: "",
        roomCertificateForm: "",
        hasOwnershipCertificate: "",
        certificateNumber: "",
        ownerName: ""
      },
      insertRules: {
        name: [
          {
            required: true,
            message: "楼宇名称不能为空",
            trigger: "blur"
          }
        ],
        unitCode: [
          {
            required: true,
            message: "单元楼不能为空",
            trigger: "change"
          }
        ],
        floors: [
          {
            required: true,
            message: "层数不能为空",
            trigger: "blur"
          }
        ],
      },
      operateType: "insert",
  
      fatherAgenciesOptionData: [],
      typeOptionData: [],
      query: {
        name: "",
        account: ""
      },
      userData: [], //用户数据
      pageNum: 0,
      pageSize: 10,
      totalSize: 0
    };
  },

  activated() {

    if (this.$route.query.operateType == "update") {
      this.operateType = "update";
      // 获取房间信息详情
      this.getbuildingXiangQing();
    } else {
      // 数据清空
      for (let i in this.reinsertForm) {
        this.reinsertForm[i] = "";
      }
      this.operateType = "insert";
    }

    //刚进入页面加载
    // this.queryUserList();
    this.getFatherAgenciesOptionData("");

  },
  mounted: function () {
    //初始化选项数据
    this.getAgencyTypeOptionData();
  },

  methods: {
    // 楼宇信息详情
    async getbuildingXiangQing() {
      let res = await getInDetail(this.$route.query.id);
      console.log(res, "房间详情");
      for (let i in res) {
        if (res[i] == 0 && i != 'isPublic' && i!='hasOwnershipCertificate') { //isPublic字段，其他所有字段为0都设置为空字符串
          res[i] = ''
        }
      }
      this.reinsertForm = res;
    },
    //级联选择器获取焦点
    cascaderClick() {
      this.getAgencyTypeOptionData();
      this.props.lazy = true;
    },
    handleChange(val) {
      console.log(val);
      this.reinsertForm.criCode = val[val.length - 1];
    },
    /**
     *  新增
     */
    onSubmit() {

      let that = this;
      this.reinsertForm.residentialId = localStorage.getItem("XiaoQuId");
      console.log(this.reinsertForm, "新增信息");
      this.$refs["reinsertForm"].validate(valid => {
        if (valid) {
          addroom(that.reinsertForm).then(res => {
            console.log(res, "新增接口返回信息");
            if (res.data.code == 200) {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.goBack();
            } else {
              if (res.data.message == "值重复") res.data.message = "机构名称不能重复";
              this.$message({
                message: res.data.message,
                type: "warning"
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     *  修改
     */
    onSubmitUpdate() {
      // this.reinsertForm.residentialId = localStorage.getItem("XiaoQuId");
      console.log(this.reinsertForm, "修改信息");
      this.reinsertForm.id = this.$route.query.id;
      updateinstInfo(this.reinsertForm).then(res => {
        console.log(res, '修改');
        if (res.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
    },

    /**
     *  上一页
     */
    goBack() {
      this.$router.back(-1);
      // this.$router.push({
      //   path: "/residential/reDetail",
      //   query: {
      //     id: this.$route.query.id,
      //     operateType: 'binding'
      //   }
      // });
    },



    /**
     * 获取下拉菜单数据
     */
    async getFatherAgenciesOptionData(name) {
      let arr = [
        "building_toward",
        "room_layout",
        "ownership_type",
        "decoration_situation",
        "ownership",
        "room_certificate_form"
      ];
      arr.forEach(async el => {
        let res = await getXiaLaList(el);
        let data = [];
        if (res.length != 0) {
          res.forEach(item => {
            data.push({
              name: item.name,
              type: Number(item.value)
            });
          });
        }
        // 房间朝向
        if (el == "building_toward") this.towardData = data;
        // 房间布局
        else if (el == "room_layout") this.layoutData = data;
        // 权属类型
        else if (el == "ownership_type") this.ownershipTypeData = data;
        // 装修情况
        else if (el == "decoration_situation")
          this.decorationSituationData = data;
        // 房屋归属
        else if (el == "ownership") this.ownershipData = data;
        //产权证书
        else if (el == "room_certificate_form") {
          this.roomCertificateFormData = data;
        }
        console.log(data, "下来数据");
      });
      // 所在楼宇
      this.buildingIdData = [];
      var id = localStorage.getItem("XiaoQuId");
      let res = await getAddedUserList({ residentialQuartersId: id });
      console.log(res, "楼宇列表");
      res.list.forEach(el => {
        this.buildingIdData.push({
          name: el.name,
          type: el.id
        });
      });
      if (this.$route.query.operateType == "update") {
      } else {
        this.$set(this.reinsertForm, 'buildingId', this.$route.query.buildingId * 1)
      }

      //单元楼
      this.unitCodeData = [
        { name: "1单元", type: 1 },
        { name: "2单元", type: 2 },
        { name: "3单元", type: 3 },
        { name: "4单元", type: 4 },
        { name: "5单元", type: 5 },
        { name: "6单元", type: 6 },
        { name: "7单元", type: 7 },
        { name: "8单元", type: 8 },
      ];
      this.hasOwnershipCertificateData = [
        { name: "没有", type: 0 },
        { name: "有", type: 1 },
      ];
    },
    dgfun(res) {
      let arr = [];
      res.forEach(el => {
        // 如果有孩子们，继续遍历
        if (el.childrenList != null) {
          el.childrenList = this.dgfun(el.childrenList);
        }
        arr.push({
          value: el.criCode,
          label: el.criName,
          children: el.childrenList
        });
      });
      return arr;
    },
    /**
     * 获取类型字典数据
     */
    getAgencyTypeOptionData() {
      // 获取省份信息
      getcityList("000000").then(res => {
        this.options = [];
        res.forEach(el => {
          this.options.push({
            value: el.criCode,
            label: el.criName
          });
        });
      });
      getDictionaryList("agency_type").then(res => {
        this.typeOptionData = res.data;
      });
    }

    //按条件查询菜单列表
    // queryUserList() {
    //   getUserList(
    //     this.query.userCode,
    //     this.query.userName,
    //     "1",
    //     this.pageNum,
    //     this.pageSize
    //   ).then(res => {
    //     this.userData = res.list;
    //     this.pageNum = res.pageNum;
    //     this.pageSize = res.pageSize;
    //     this.totalSize = res.total;
    //   });
    // }
  }
};
</script>
<style lang="less" scoped>
.szdqBox {
  display: flex;

  .addressStyle {
    width: 350px;
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;

    /deep/ label {
      width: 33%;

      select {
        width: 100%;
      }
    }
  }
}

.insertPopulation {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}

.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>